import { Component,OnInit } from '@angular/core';
import {Store,Select} from '@ngxs/store';
import {Observable} from 'rxjs';
import {SetNav,UserGuidState} from '../app.state';
import { Router,ActivatedRoute } from '@angular/router';
import {RollService} from '../my-service/roll.service'
import {UtilService} from '../my-service/util.service';

@Component({
  selector: 'app-joinRoster',
  templateUrl: './join-roster.component.html',
  styleUrls: ['./join-roster.component.css']
})
export class JoinRosterComponent implements OnInit {
  @Select(UserGuidState) userGuid$: Observable<any>; //获取用户guid和登录状态
  userGuid:string;
  classGuid:string;
  readImg:string;
  isJoin=false;
  classInfo={
    ClassName:'',
    CreateTime:'',
    EndTime:'',
    Creator:'',
    Number:0,
    CoverUrl:''
  };
  constructor(
    private store:Store,
    private router:ActivatedRoute,
    private route:Router,
    private rollService:RollService,
    private utilService:UtilService
  ) {
    this.readImg = this.utilService.readImgUrl;
    this.store.dispatch(new SetNav('enter'));
    this.userGuid$.subscribe(res=>{
      this.userGuid=res.userGuid;
    })
  }
  //获取班级信息
  ngOnInit() {
    this.classGuid = this.router.snapshot.params["id"];
    this.rollService.getJoinClass(this.userGuid).then(res=>{
      if(res.status==1){
        res.data.forEach(item=>{
          if(item.FK_ClassGuid==this.classGuid){
            this.isJoin=true;
            return;
          }
        })
      }
    });
    //获取班级信息
    this.rollService.getClassList('"'+this.classGuid+'"').then(res=>{
      if(res.status==1){
        this.classInfo = res.data[0];
        this.classInfo.CreateTime=this.utilService.changDateString(this.classInfo.CreateTime);
        this.classInfo.EndTime=this.utilService.changDateString(this.classInfo.EndTime);
      }
    })
  }
  //加入班级
  joinClass(){
    if(!this.isJoin){
    let data = {
      FK_ClassGuid:this.classGuid,
      FK_UserGuid:this.userGuid
    };
    this.rollService.joinClass(data).then(res=>{
      if(res.status==1){
          window.alert('加入班级成功');
          //返回班级详情
        this.route.navigate(['/home/rosterInfo',this.classGuid]);
      }else {
        window.alert(res.err);
      }
    })
  }
  }
}
